package cn.lg.soar.boot.fc.service.impl;

import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.database.query.SqueryWapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;
import cn.lg.soar.database.base.service.impl.BaseServiceImpl;
import cn.lg.soar.boot.fc.mapper.ProcessNodeMapper;
import cn.lg.soar.boot.fc.entity.ProcessNode;
import cn.lg.soar.boot.fc.service.ProcessNodeService;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 流程节点表
 * @author ZhuanZ（无密码）
 * @since 2025-01-14
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Service
public class ProcessNodeServiceImpl extends BaseServiceImpl<ProcessNodeMapper, ProcessNode> implements ProcessNodeService {


    private SqueryWapper<ProcessNode> squeryWapper;
    /**
     * 更新
     *
     * @param updateFormList
     * @return
     */
    public HttpResult<Void> updateNodeList(List<ProcessNode> updateFormList) {
        if (squeryWapper == null) {
            squeryWapper = new SqueryWapper<>(ProcessNode.class);
        }
        QueryWrapper<ProcessNode> wrapper = Wrappers.query();
        List<String> f = new ArrayList<>();
        f.add("processId-eq~"+updateFormList.get(0).getProcessId());
        List<String> orderBy = new ArrayList<>();
        orderBy.add("orders");
        squeryWapper.setWhere(f, wrapper);
        squeryWapper.setOrderBy(orderBy, wrapper);
        List<ProcessNode> list = super.list(wrapper);
        for (ProcessNode updateForm : updateFormList){
            if(updateForm.getId() != null){
                AssertUtil.isTrue(super.updateById(updateForm), "更新失败");
            }else{
                AssertUtil.isTrue(super.save(updateForm), "创建失败");
            }
        }
        for (ProcessNode processNode : list){
            boolean is = false;
            for (ProcessNode updateForm : updateFormList){
                if(updateForm.getId() != null){
                    if(Objects.equals(processNode.getId(), updateForm.getId())){
                        is =false;
                        break;
                    }else{
                        is = true;
                    }
                }
            }
            if(is){
                List<Long> ids = new ArrayList<>();
                ids.add(processNode.getId());
                AssertUtil.isTrue(super.removeByIds(ids), "删除失败");
            }
        }
        return HttpResult.success("更新流程成功");
    }

}
